package com.lb.design.pattern.factorypattern.factory;

import com.lb.design.pattern.factorypattern.ClassUtils;
import com.lb.design.pattern.factorypattern.pojo.Human;


import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: liubin
 * Date: 2017-12-29
 * Time: 下午 5:07
 */
public class HumanFactory {


    //定义一个hashmap,存放初始化过的human对象
    private static HashMap<String,Human> humans = new HashMap<String, Human>();


    public static Human createHuman(Class c){
        Human human = null;
        try {
            //如果map中存在，就不需要初始化了
            if(humans.containsKey(c.getSimpleName())){
                human = humans.get(c.getSimpleName());
            }else {
                //初始化
                human = (Human) Class.forName(c.getName()).newInstance();
                //放到map中
                humans.put(c.getSimpleName(),human);
            }


        } catch (IllegalAccessException e) {
            System.out.println("必须指定认得颜色");
            e.printStackTrace();
        } catch (InstantiationException e) {
            System.out.println("人种定义有问题");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            System.out.println("你的人种找不到");
            e.printStackTrace();
        }
        return human;
    }


    public static Human createHuman(){
        Human human = null;
        List<Class> humans = ClassUtils.getAllClassByInterface(Human.class);
        Random random = new Random();
        int anInt = random.nextInt(humans.size());
        human= createHuman(humans.get(anInt));
        return human;
    }

}
